package com.bawei.lookfor2204a.view.activity.watch

import android.graphics.Color
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import coil.load
import coil.transform.CircleCropTransformation
import com.ayvytr.adapter.smart
import com.bawei.lookfor2204a.R
import com.bawei.lookfor2204a.base.BaseActivity
import com.bawei.lookfor2204a.databinding.ActivityWatchBinding
import com.bawei.lookfor2204a.model.FindAllGiftBean
import com.bawei.lookfor2204a.model.MessageBean
import com.blankj.utilcode.util.ToastUtils
import com.kd.easybarrage.Barrage

/**
 * 观看直播和录播页面
 */
class WatchActivity : BaseActivity<WatchViewModel, ActivityWatchBinding>(R.layout.activity_watch) {

    // 消息聊天室适配器
    val messageAdapter = smart(
        mutableListOf<MessageBean>(),
        R.layout.item_message,
        {item, position ->
            // 显示头像
            findViewById<ImageView>(R.id.iv_tou).load(item.avatar) {
                transformations(CircleCropTransformation()) // 圆形
            }
            // 显示用户昵称
            findViewById<TextView>(R.id.tv_nickname).text = item.nickName
            // 显示消息内容
            findViewById<TextView>(R.id.tv_content).text = item.content
        }
    ){}

    // 选中礼物标示
    var giftIndex = -1

    // 礼物网格适配器
    val giftAdapter = smart(
        mutableListOf<FindAllGiftBean.Result>(),
        R.layout.item_gift,
        {item, position ->
            // 处理选中礼物的背景
            val linearLayout = findViewById<LinearLayout>(R.id.ll_root)
            if (giftIndex == position) {
                linearLayout.setBackgroundColor(Color.BLUE)
            } else {
                linearLayout.setBackgroundColor(Color.BLACK)
            }
            // 显示礼物图标
            findViewById<ImageView>(R.id.iv_gift_image).load(item.imageUrl)
            // 显示礼物名称
            findViewById<TextView>(R.id.tv_gift_name).text = item.name
            // 显示礼物价格
            findViewById<TextView>(R.id.tv_gift_price).text = "${item.price}v币"
        }
    ){}.click { item, position ->
        songLi(item, position)
        /*// 显示赠送的礼物
        binding.ivGiftShow.visibility = View.VISIBLE
        binding.ivGiftShow.load(item.imageUrl)
        // 加载赠送礼物动画
        val animation = AnimationUtils.loadAnimation(this@WatchActivity, R.anim.gift_anim)
        // 设置动画监听
        animation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(p0: Animation?) {

            }

            override fun onAnimationEnd(p0: Animation?) {
                // 隐藏礼物
                binding.ivGiftShow.visibility = View.GONE
            }

            override fun onAnimationRepeat(p0: Animation?) {
            }

        })
        // 播放动画
        binding.ivGiftShow.startAnimation(animation)*/
    }

    private fun songLi(item: FindAllGiftBean.Result, position: Int) {
        giftIndex = position
        giftAdapter.notifyDataSetChanged()
        binding.ivGiftShow.load(item.imageUrl)
    }

    override fun initData() {
        // 观看直播
        viewModel.watchLiveSuccess.observe(this, {
            ToastUtils.showShort(it.message)
            if (it.result != null) {
                // 给播放器设置拉流地址
                binding.gsy.setUp(it.result.liveStreamUrl, true, "")
                // 隐藏播放器的返回按钮
                binding.gsy.backButton.visibility = View.GONE
                // 开始拉流
                binding.gsy.startPlayLogic()
            }
        })

        // 更新礼物网格数据
        viewModel.findAllGiftSuccess.observe(this, {
            giftAdapter.update(it.result)
        })
    }

    override fun initView() {
        // 观看
        watch()

        // 礼物
        gift()

        // 弹幕
        barrage()

        // 消息聊天室
        roomMessage()

        // 退出页面
        exit()
    }

    private fun exit() {
        binding.ivClose.setOnClickListener { finish() }
    }

    private fun roomMessage() {
        binding.recMessage.layoutManager = LinearLayoutManager(this)
        binding.recMessage.adapter = messageAdapter
        messageAdapter.update(viewModel.messageList)
    }

    private fun barrage() {
        binding.btnSend.setOnClickListener {
            // 获取弹幕内容
            val dmStr = binding.etInput.text.toString()
            // 涉黄涉证的处理
            if (dmStr.contains("黄") || dmStr.contains("政") || dmStr.contains("毒")) {
                ToastUtils.showShort("包含敏感词")
            } else {
                // 发送弹幕
                binding.barrageView.addBarrage(Barrage(dmStr))
                // 把输入框中的内容添加到消息聊天室
                messageAdapter.add(
                    MessageBean("https://pics0.baidu.com/feed/72f082025aafa40f1e91cf8f819a3d4179f0191c.jpeg?token=81bcc4eecc0fceebc7ac9760f34f815e", "猪八戒", dmStr)
                )
                // 滚动消息列表
                binding.recMessage.scrollToPosition(messageAdapter.itemCount - 1)
            }
            // 清空输入框
            binding.etInput.text.clear()
        }
    }

    private fun watch() {
        // 获取上一个页面传递过来的值
        val liveId = intent.getIntExtra("liveId", 0)
        val liveStatus = intent.getIntExtra("liveStatus", 0)
        val liveTitle = intent.getStringExtra("liveTitle")
        if (liveStatus == 2) {
            // 录播
            binding.gsy.backButton.visibility = View.GONE
            binding.gsy.setUp(
                "http://10.59.9.24/live-platform/recordVideo/$liveId",
                true,
                liveTitle
            )
            binding.gsy.startPlayLogic()
        } else {
            // 观看直播
            viewModel.watchLive(liveId)
        }
    }

    private fun gift() {
        // 礼物网格布局管理器
        binding.recGift.layoutManager = GridLayoutManager(this, 3)
        // 礼物网格绑定适配器
        binding.recGift.adapter = giftAdapter
        // 请求礼物数据
        viewModel.findAllGift()

        binding.ivGift.setOnClickListener {
            // 显示礼物
            binding.llGift.visibility = View.VISIBLE
        }
        binding.ivCloseGift.setOnClickListener {
            // 隐藏礼物
            binding.llGift.visibility = View.GONE
        }
        binding.tvZengSong.setOnClickListener {
            if (giftIndex == -1) {
                ToastUtils.showShort("请选择要赠送的礼物")
                return@setOnClickListener
            }
            binding.ivGiftShow.visibility = View.VISIBLE
            val animation = AnimationUtils.loadAnimation(this@WatchActivity, R.anim.gift_anim)
            animation.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(p0: Animation?) {

                }

                override fun onAnimationEnd(p0: Animation?) {
                    binding.ivGiftShow.visibility = View.GONE
                }

                override fun onAnimationRepeat(p0: Animation?) {
                }

            })
            binding.ivGiftShow.startAnimation(animation)
        }
    }

    override fun getViewModel() = WatchViewModel::class.java

    override fun onDestroy() {
        super.onDestroy()
        // 避免内存泄露
        binding.barrageView.destroy()
    }
}